﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using SufeiUtil_Core;
using System.IO;
using System.Text.RegularExpressions;
using System.Reflection;
using System.Net;
using System.Speech.Synthesis;
using System.Globalization;
using System.Linq;
using System.CodeDom.Compiler;
using Microsoft.CSharp;

namespace 封包测试工具
{
    public partial class Fm_Main : Form
    {
        public Fm_Main()
        {
            InitType();
            InitializeComponent();
            ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
        }
        #region  定义封包所需变量
        private HttpHelper httpHelper = new HttpHelper();
        private HttpItem httpItem = new HttpItem();
        private HttpResult httpResult = new HttpResult();
        //string cookies = string.Empty;
        Point M_Mouse;
        int index=-1;

        #endregion

        #region 控件事件

        private void Fm_Main_Load(object sender, EventArgs e)
        {
            cmb_Method.SelectedIndex = cmb_Encoding.SelectedIndex = cmb_Cookies.SelectedIndex = 0;
            this.Text = this.Text.Replace("#版本号", "alpha 1.1(" + GetVersion() + ")");

            cmbEncoding.SelectedIndex = cmbConvert.SelectedIndex = cmbWebProxy.SelectedIndex = cmbFanyiType.SelectedIndex = 0;

        }
        private string GetVersion()
        {
            //string ver = string.Empty;
            //var appIdenity = AppDomain.CurrentDomain.ActivationContext.Identity;


            //return getstringmiddle(appIdenity.FullName.ToString(), "Version=", ",");
            //1.0.0.11,

            return System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
        }
        private void btn_Submit_Click(object sender, EventArgs e)
        {
            //ServicePointManager.ServerCertificateValidationCallback = (s, cert, chain, err) => true;
            //ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
            txt_Returndata.Text = "";
            txt_ReturnCookies.Text = "";
            txt_ReturnHeader.Text = "";
            time.Text = "请求中";
            string status = "";
            DateTime start = DateTime.Now;
            if (txt_PostUrl.Text.IndexOf("http") == -1 && txt_PostUrl.Text.IndexOf("HTTP") == -1)
            {
                txt_PostUrl.Text = "http://" + txt_PostUrl.Text;
            }
            httpItem.Method =cmb_Method.Text;
            if (cmb_Method.Text == "POST")
            {
                httpItem.ContentType = "application/x-www-form-urlencoded";
            }
            httpItem.Postdata = txt_PostData.Text;
            httpItem.URL = txt_PostUrl.Text;
            httpItem.ResultType = ResultType.Byte;
            switch (cmb_Encoding.SelectedIndex)
            {
                case 0: httpItem.Encoding = null; break;
                case 1: httpItem.Encoding = Encoding.GetEncoding("GBK"); break;
                case 2: httpItem.Encoding = Encoding.UTF8; break;
                default:
                    try
                    {
                        httpItem.Encoding = Encoding.GetEncoding(cmb_Encoding.Text.ToString());
                    }
                    catch (SystemException exception)
                    {
                        MessageBox.Show(exception.Message + "\n将切换到自动识别模式", "编码注册失败");
                        cmb_Encoding.SelectedIndex = 0;
                        httpItem.Encoding = null;
                    }
                    break;
            }
            if (cmb_Cookies.SelectedIndex == 0)
            {
                httpItem.Cookie = $"{httpItem.Cookie}{txt_Cookies.Text}";
            }
            else
            {
                httpItem.Cookie = txt_Cookies.Text;
            }
            //Console.WriteLine("COOKIES：" + httpItem.Cookie);
            if (txt_Header.Text != "")
            {
                foreach (string str in txt_Header.Text.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries))
                {
                    Console.WriteLine(str);
                    string[] content = str.Split(new string[] { ":" }, StringSplitOptions.RemoveEmptyEntries);
                    if (content.Length >= 2)
                    {
                        string headkey = content[0].ToLower();
                        string headval = content[1].TrimStart();
                        for (int i = 2; i < content.Length; i++)
                        {
                            headval += ":" + content[i];
                        }
                        switch (headkey)
                        {
                            case "connection": break;
                            case "referer": httpItem.Referer = headval; break;
                            case "user-agent": httpItem.UserAgent = headval; break;
                            case "contenttype": httpItem.ContentType = headval; break;
                            case "content-type": httpItem.ContentType = headval; break;
                            case "accept": httpItem.Accept = headval; break;
                            case "x-requested-with": httpItem.Header.Add("X-Requested-With", "XMLHttpRequest"); break;
                            default:
                                httpItem.Header.Add(content[0], headval); break;
                        }
                    }
                }
            }
            if (cmbWebProxy.Text != "不使用代理")
            {
                if (cmbWebProxy.Text != "IE代理")
                {
                    httpItem.ProxyIp = "";
                    httpItem.WebProxy = new WebProxy(cmbWebProxy.Text);
                }
                else
                {
                    httpItem.ProxyIp = "ieproxy";
                }
            }
            else
            {
                httpItem.ProxyIp = "";
                httpItem.WebProxy = null;

            }


            httpItem.Timeout = int.Parse(txt_timeout.Text) * 1000;
            httpItem.ReadWriteTimeout = int.Parse(txt_writetimeout.Text) * 1000;
            httpItem.Allowautoredirect = chk_Allowautoredirect.Checked;
            httpResult = httpHelper.GetHtml(httpItem);
            time.Text = "请求完成";
            if (httpResult.Cookie != null)
            {
                txt_ReturnCookies.Text = httpResult.Cookie;
                httpItem.Cookie = httpResult.Cookie;
            }
            if (httpResult.Html != null)
            {

                if (httpResult.Header != null && httpResult.Header.ToString().IndexOf("Content-Type: image") != -1)
                {
                    MemoryStream me = new MemoryStream(httpResult.ResultByte);
                    Image bit = Image.FromStream(me);
                    if (bit.Width > pic_return_pic.Width || bit.Height > pic_return_pic.Height)
                    {
                        pic_return_pic.SizeMode = PictureBoxSizeMode.StretchImage;
                    }
                    else {
                        pic_return_pic.SizeMode = PictureBoxSizeMode.Normal;
                    }
                    pic_return_pic.Image = bit;
                    pic_return_pic.Visible = true;

                }
                else
                {
                    txt_Returndata.Text = httpResult.Html;
                    pic_return_pic.Visible = false;
                }


            }

            if (httpResult.Header != null)
            {
                txt_ReturnHeader.Text = httpResult.Header.ToString();


                for (int i = 0; i < httpResult.Header.AllKeys.Length; i++)
                {
                    string key = httpResult.Header.AllKeys[i];
                    string value = httpResult.Header[i];
                    switch (key)
                    {
                        case "Server":
                            status += "  网站环境:" + value; break;
                        case "X-Powered-By":
                            status += "  程序支持:" + value; break;
                        case "Last-Modified":
                            status += "  最后修改:" + GMT2Local(value).ToString(); break;
                        case "Content-Length":
                            status += "  文件大小:" + FormatBytes(value).ToString(); break;
                        default:
                            break;
                    }
                }

            }
            

            DateTime endtime = DateTime.Now;
            time.Text = "本次耗时：" + Math.Round(endtime.Subtract(start).TotalSeconds, 2).ToString() + "s\t " + status;
        }

        /// <summary>  
        /// GMT时间转成本地时间  
        /// </summary>  
        /// <param name="gmt">字符串形式的GMT时间</param>  
        /// <returns></returns>  
        public DateTime GMT2Local(string gmt)
        {
            DateTime dt = DateTime.MinValue;
            try
            {
                string pattern = "";
                if (gmt.IndexOf("+0") != -1)
                {
                    gmt = gmt.Replace("GMT", "");
                    pattern = "ddd, dd MMM yyyy HH':'mm':'ss zzz";
                }
                if (gmt.ToUpper().IndexOf("GMT") != -1)
                {
                    pattern = "ddd, dd MMM yyyy HH':'mm':'ss 'GMT'";
                }
                if (pattern != "")
                {
                    dt = DateTime.ParseExact(gmt, pattern, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.AdjustToUniversal);
                    dt = dt.ToLocalTime();
                }
                else
                {
                    dt = Convert.ToDateTime(gmt);
                }
            }
            catch
            {
            }
            return dt;
        }
        public string FormatBytes(string bytesstr)
        {
            long bytes = Convert.ToInt64(bytesstr);
            string[] Suffix = { "Byte", "KB", "MB", "GB", "TB" };
            int i = 0;
            double dblSByte = bytes;
            if (bytes > 1024)
                for (i = 0; (bytes / 1024) > 0; i++, bytes /= 1024)
                    dblSByte = bytes / 1024.0;
            return String.Format("{0:0.##}{1}", dblSByte, Suffix[i]);
        }
        private void 复制文本ToolStripMenuItem_Click(object sender, EventArgs e)
        {

            Control control = cms_txt.SourceControl;
            if (control.Text != "")
            {
                Clipboard.SetText(control.Text);
            }
            else Clipboard.SetText(" ");
        }

        private void 粘贴ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Control control = cms_txt.SourceControl;
            control.Text = Clipboard.GetText();

        }

        private void 清空ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Control control = cms_txt.SourceControl;
            control.Text = "";
        }

        private void txt_timeout_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (((int)e.KeyChar < 48 || (int)e.KeyChar > 57) && (int)e.KeyChar != 8 && (int)e.KeyChar != 46)
                e.Handled = true;
        }

        private void txt_writetimeout_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (((int)e.KeyChar < 48 || (int)e.KeyChar > 57) && (int)e.KeyChar != 8 && (int)e.KeyChar != 46)
                e.Handled = true;
        }

        private void btn_getclipboard_Click(object sender, EventArgs e)
        {
            txt_PostUrl.Text = txt_PostData.Text = txt_Header.Text = txt_Cookies.Text = null;
            string clipStr = Clipboard.GetText();
            string[] strarray = clipStr.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None);
            if (strarray.Length == 1)
            {
                txt_PostUrl.Text = clipStr;
                return;
            }
            for (int i = 0; i < strarray.Length; i++)
            {
                string str = strarray[i];
                if (i==0)
                {
                    string[] strs = str.Split(new string[] { " " },StringSplitOptions.RemoveEmptyEntries);
                    if (strs.Length>1)
                    {
                        SelectMethod(strs[0]);
                        if (strs[0] == cmb_Method.Text)
                        {
                            txt_PostUrl.Text = strs[1];
                        }
                    }
                }
                if (str.StartsWith("Request Method"))
                {
                    string method = str.Substring(15, str.Length - 15);
                    SelectMethod(method);
                }

                else if (str.StartsWith("Request URL:"))
                {
                    txt_PostUrl.Text = str.Substring(12, str.Length - 12).Trim();
                }
                else if (str.StartsWith("Host"))
                {
                    if (!txt_PostUrl.Text.ToLower().StartsWith("http:") && !txt_PostUrl.Text.ToLower().StartsWith("https:"))
                    {
                        string host = str.Substring(5, str.Length - 5).Trim();
                        txt_PostUrl.Text = "http://" + host + txt_PostUrl.Text;
                    }

                }
                else if (str.StartsWith("Cookie"))
                {
                    if (str.StartsWith("Cookie:"))
                    {
                        txt_Cookies.Text = str.Substring(7, str.Length - 7).Trim();
                    }
                    else
                    {
                        txt_Cookies.Text = str.Split(new string[] { ": " }, StringSplitOptions.RemoveEmptyEntries)[1];
                    }

                }
                else if (str.StartsWith("Accept") || str.StartsWith("Accept-Language") || str.StartsWith("User-Agent") || str.StartsWith("Accept-Encoding") || str.StartsWith("Connection: Keep-Alive") || str.StartsWith("X-Requested-With") || str.StartsWith("Referer") || str.StartsWith("Origin") || str.StartsWith("DNT") || str.StartsWith("Content-Type"))
                {
                    txt_Header.AppendText(str + "\r\n");
                }
                else if (str.StartsWith("Content-Length") || str.StartsWith("Connection") || str.StartsWith("Request Headersview") || str.StartsWith("Status Code") || str.StartsWith("Remote Address"))
                { }
                else if (regHead.IsMatch(str) && i != strarray.Length - 1)
                {
                    txt_Header.AppendText(str + "\r\n");
                }
                else
                {
                    if (i > 0 && strarray[i - 1] == "")
                    {
                        txt_PostData.Text = str;
                    }
                    else
                    {
                        if (!string.IsNullOrEmpty(txt_PostData.Text))
                        {
                            txt_PostData.Text += "\r\n" + str;
                        }
                    }

                }
            }

            txt_PostUrl.Text = txt_PostUrl.Text.Replace("\r", null);
        }
        private void SelectMethod(string Method)
        {
            cmb_Method.SelectedIndex = 0;
            for (int i = 0; i < cmb_Method.Items.Count; i++)
            {
                if (cmb_Method.Items[i].ToString()==Method.ToUpper())
                {
                    cmb_Method.SelectedIndex = i;
                    break;
                }
            }
        }
        #endregion


        private void button2_Click(object sender, EventArgs e)
        {
            ofd.InitialDirectory = Application.ExecutablePath;
            ofd.RestoreDirectory = true;
            ofd.Title = "请选择匹配文本的文件";
            DialogResult result = ofd.ShowDialog();
            if (result == DialogResult.OK)
            {
                txt_regex_txt.Text = "成功打开";
                StreamReader stream = new StreamReader(ofd.FileName, Encoding.Default);
                txt_regex_txt.Text = stream.ReadToEnd();
            }

        }
        Regex regHead = new Regex("^(\\w+): (\\w+)\\S");
        private void btn_matching_Click(object sender, EventArgs e)
        {
            if (txt_regex.Text == string.Empty)
            {
                status.Text = "正则文本不能为空";
                txt_regex.Focus();
                return;
            }
            if (txt_regex_txt.Text == string.Empty)
            {
                status.Text = "源文本不能为空";
                txt_regex_txt.Focus();
                return;
            }
            DateTime start = DateTime.Now;
            Regex reg;
            DateTime endtime;
            lvMatchecs.Columns.Clear();
            lvMatchecs.Items.Clear();
            lvMatchecs.Columns.Add("ID", "序号", 60);
            lvMatchecs.Columns.Add("匹配文本", 100);
            tabControl2.SelectedIndex = 1;
            try
            {
                reg = new Regex(txt_regex.Text, (chkRegexIgnoreCase.Checked ? 0 : RegexOptions.IgnoreCase) | (chkRegexMultiline.Checked ? RegexOptions.Multiline : 0));
            }
            catch (Exception)
            {
                endtime = DateTime.Now;
                time.Text = "本次耗时：" + endtime.Subtract(start).TotalSeconds.ToString() + "s";
                status.Text = "正则创建失败，请检查正则语句";
                return;

            }
            MatchCollection matches = reg.Matches(txt_regex_txt.Text);
            for (int n = 0; n < matches.Count; n++)
            {
                GroupCollection group = matches[n].Groups;
                while (lvMatchecs.Columns.Count - 1 < group.Count)
                {
                    lvMatchecs.Columns.Add("子匹配文本" + (lvMatchecs.Columns.Count - 1).ToString(), 120);
                }
                string[] strs = new string[group.Count + 1];
                strs[0] = (n + 1).ToString();
                for (int i = 0; i < group.Count; i++)
                {
                    strs[i + 1] = group[i].Value;
                }

                ListViewItem item = new ListViewItem(strs);
                lvMatchecs.Items.Add(item);
            }
            endtime = DateTime.Now;
            time2.Text = "本次耗时：" + Math.Round(endtime.Subtract(start).TotalSeconds, 2).ToString() + "s";
            status.Text = "匹配正常   匹配数量：" + matches.Count.ToString() + "    子匹配数量：" + (lvMatchecs.Columns.Count - 2).ToString();

        }

        private void 复制整行ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            StringBuilder strbuilder = new StringBuilder();

            for (int i = 0; i < lvMatchecs.SelectedItems.Count; i++)
            {
                if (i == 0)
                {
                    if (!chk_noid.Checked && !chk_nomatch.Checked)
                    {
                        for (int n = 0; n < lvMatchecs.Columns.Count; n++)
                        {

                            if (n != lvMatchecs.Columns.Count - 1)
                            {
                                strbuilder.Append(lvMatchecs.SelectedItems[i].SubItems[n].Text + "\t");
                            }
                            else strbuilder.Append(lvMatchecs.SelectedItems[i].SubItems[n].Text);
                        }
                    }
                    else if (chk_noid.Checked && !chk_nomatch.Checked)
                    {
                        for (int n = 1; n < lvMatchecs.Columns.Count; n++)
                        {

                            if (n != lvMatchecs.Columns.Count - 1)
                            {
                                strbuilder.Append(lvMatchecs.SelectedItems[i].SubItems[n].Text + "\t");
                            }
                            else strbuilder.Append(lvMatchecs.SelectedItems[i].SubItems[n].Text);
                        }
                    }
                    else if (chk_noid.Checked && chk_nomatch.Checked)
                    {
                        for (int n = 2; n < lvMatchecs.Columns.Count; n++)
                        {

                            if (n != lvMatchecs.Columns.Count - 1)
                            {
                                strbuilder.Append(lvMatchecs.SelectedItems[i].SubItems[n].Text + "\t");
                            }
                            else strbuilder.Append(lvMatchecs.SelectedItems[i].SubItems[n].Text);
                        }
                    }
                }
                else
                {
                    strbuilder.Append("\n");
                    if (!chk_noid.Checked && !chk_nomatch.Checked)
                    {
                        for (int n = 0; n < lvMatchecs.Columns.Count; n++)
                        {

                            if (n != lvMatchecs.Columns.Count - 1)
                            {
                                strbuilder.Append(lvMatchecs.SelectedItems[i].SubItems[n].Text + "\t");
                            }
                            else strbuilder.Append(lvMatchecs.SelectedItems[i].SubItems[n].Text);
                        }
                    }
                    else if (chk_noid.Checked && !chk_nomatch.Checked)
                    {
                        for (int n = 1; n < lvMatchecs.Columns.Count; n++)
                        {

                            if (n != lvMatchecs.Columns.Count - 1)
                            {
                                strbuilder.Append(lvMatchecs.SelectedItems[i].SubItems[n].Text + "\t");
                            }
                            else strbuilder.Append(lvMatchecs.SelectedItems[i].SubItems[n].Text);
                        }
                    }
                    else if (chk_noid.Checked && chk_nomatch.Checked)
                    {
                        for (int n = 2; n < lvMatchecs.Columns.Count; n++)
                        {

                            if (n != lvMatchecs.Columns.Count - 1)
                            {
                                strbuilder.Append(lvMatchecs.SelectedItems[i].SubItems[n].Text + "\t");
                            }
                            else strbuilder.Append(lvMatchecs.SelectedItems[i].SubItems[n].Text);
                        }
                    }
                }

            }
            Clipboard.SetText(strbuilder.ToString());


        }

        private void listView1_MouseUp(object sender, MouseEventArgs e)
        {
            index = -1;
            if (e.Button == MouseButtons.Right)
            {
                M_Mouse = lvMatchecs.PointToClient(MousePosition);
                ListViewItem lstrow = lvMatchecs.GetItemAt(M_Mouse.X, M_Mouse.Y);
                if (lstrow == null)
                {
                    cms_regx.Items["copy"].Text = "复制";
                }
                else
                {
                    ListViewItem.ListViewSubItem lstcol = lstrow.GetSubItemAt(M_Mouse.X, M_Mouse.Y);
                    string strText = lstcol.Text;
                    if (strText.Length > 10)
                    {
                        strText = strText.Substring(0, 10) + "...";
                    }
                    cms_regx.Items["copy"].Text = "复制“" + strText + "”";

                    index=lstrow.SubItems.IndexOf(lstcol);

                }
                cms_regx.Show(MousePosition);

            }
        }

        private void 复制整列ToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void listView1_ColumnClick(object sender, ColumnClickEventArgs e)
        {
            index = e.Column;
            cms_regx1.Show(MousePosition);
        }
        /// <summary>
        /// 输入框
        /// </summary>
        /// <param name="Caption">标题</param>
        /// <param name="Hint">提示文本</param>
        /// <param name="Default">默认文本</param>
        /// <returns></returns>
        private string InputBox(string Caption, string Hint, string Default)
        {
            Form InputForm = new Form();
            InputForm.MinimizeBox = false;
            InputForm.MaximizeBox = false;
            InputForm.FormBorderStyle = FormBorderStyle.Fixed3D;
            InputForm.StartPosition = FormStartPosition.CenterScreen;
            InputForm.Width = 220;
            InputForm.Height = 150;
            InputForm.Text = Caption;
            Label lbl = new Label();
            lbl.Text = Hint;
            lbl.Left = 30;
            lbl.Top = 20;
            lbl.Parent = InputForm;
            lbl.AutoSize = true;
            TextBox tb = new TextBox();
            tb.Left = 30;
            tb.Top = 45;
            tb.Width = 160;
            tb.Parent = InputForm;
            tb.Text = Default;
            tb.SelectAll();
            Button btnok = new Button();
            btnok.Left = 30;
            btnok.Top = 80;
            btnok.Parent = InputForm;
            btnok.Text = "确定";
            InputForm.AcceptButton = btnok;

            btnok.DialogResult = DialogResult.OK;
            Button btncancal = new Button();
            btncancal.Left = 120;
            btncancal.Top = 80;
            btncancal.Parent = InputForm;
            btncancal.Text = "取消";
            btncancal.DialogResult = DialogResult.Cancel;
            try
            {
                if (InputForm.ShowDialog() == DialogResult.OK)
                {
                    return tb.Text;
                }
                else
                {
                    return null;
                }
            }
            finally
            {
                InputForm.Dispose();
            }
        }
        private void btn_replace_Click(object sender, EventArgs e)
        {
            string replace = InputBox("替换信息", "请输入欲替换成的文本", "$1");
            if (replace != "")
            {
                DateTime start = DateTime.Now;
                Regex regex = new Regex(txt_regex.Text, (chkRegexIgnoreCase.Checked ? 0 : RegexOptions.IgnoreCase) | (chkRegexMultiline.Checked ? RegexOptions.Multiline : 0));
                try
                {
                    txt_regex_replace.Text = regex.Replace(txt_regex_txt.Text, replace);
                    tabControl2.SelectedIndex = 2;
                    status.Text = "替换成功";
                }
                catch (Exception)
                {

                    status.Text = "替换失败";
                }
                DateTime endtime = DateTime.Now;
                time.Text = "本次耗时：" + endtime.Subtract(start).TotalSeconds.ToString() + "s";


            }


        }

        private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                cms_pic.Show(MousePosition);
            }
        }

        private void 复制到剪辑版ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Clipboard.SetImage(pic_return_pic.Image);
        }

        private void 另存为ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                pic_return_pic.Image.Save(sfd.FileName);

            }
        }

        private void 复制ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ListViewItem lstrow = lvMatchecs.GetItemAt(M_Mouse.X, M_Mouse.Y);
            ListViewItem.ListViewSubItem lstcol = lstrow.GetSubItemAt(M_Mouse.X, M_Mouse.Y);
            string strText = lstcol.Text;
            Clipboard.SetText(strText);

        }

        private void 复制全部ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            StringBuilder strbuilder = new StringBuilder();

            for (int i = 0; i < lvMatchecs.Items.Count; i++)
            {
                if (i == 0)
                {
                    if (!chk_noid.Checked && !chk_nomatch.Checked)
                    {
                        for (int n = 0; n < lvMatchecs.Columns.Count; n++)
                        {

                            if (n != lvMatchecs.Columns.Count - 1)
                            {
                                strbuilder.Append(lvMatchecs.Items[i].SubItems[n].Text + "\t");
                            }
                            else strbuilder.Append(lvMatchecs.Items[i].SubItems[n].Text);
                        }
                    }
                    else if (chk_noid.Checked && !chk_nomatch.Checked)
                    {
                        for (int n = 1; n < lvMatchecs.Columns.Count; n++)
                        {

                            if (n != lvMatchecs.Columns.Count - 1)
                            {
                                strbuilder.Append(lvMatchecs.Items[i].SubItems[n].Text + "\t");
                            }
                            else strbuilder.Append(lvMatchecs.Items[i].SubItems[n].Text);
                        }
                    }
                    else if (chk_noid.Checked && chk_nomatch.Checked)
                    {
                        for (int n = 2; n < lvMatchecs.Columns.Count; n++)
                        {

                            if (n != lvMatchecs.Columns.Count - 1)
                            {
                                strbuilder.Append(lvMatchecs.Items[i].SubItems[n].Text + "\t");
                            }
                            else strbuilder.Append(lvMatchecs.Items[i].SubItems[n].Text);
                        }
                    }
                }
                else
                {
                    strbuilder.Append("\n");
                    if (!chk_noid.Checked && !chk_nomatch.Checked)
                    {
                        for (int n = 0; n < lvMatchecs.Columns.Count; n++)
                        {

                            if (n != lvMatchecs.Columns.Count - 1)
                            {
                                strbuilder.Append(lvMatchecs.Items[i].SubItems[n].Text + "\t");
                            }
                            else strbuilder.Append(lvMatchecs.Items[i].SubItems[n].Text);
                        }
                    }
                    else if (chk_noid.Checked && !chk_nomatch.Checked)
                    {
                        for (int n = 1; n < lvMatchecs.Columns.Count; n++)
                        {

                            if (n != lvMatchecs.Columns.Count - 1)
                            {
                                strbuilder.Append(lvMatchecs.Items[i].SubItems[n].Text + "\t");
                            }
                            else strbuilder.Append(lvMatchecs.Items[i].SubItems[n].Text);
                        }
                    }
                    else if (chk_noid.Checked && chk_nomatch.Checked)
                    {
                        for (int n = 2; n < lvMatchecs.Columns.Count; n++)
                        {

                            if (n != lvMatchecs.Columns.Count - 1)
                            {
                                strbuilder.Append(lvMatchecs.Items[i].SubItems[n].Text + "\t");
                            }
                            else strbuilder.Append(lvMatchecs.Items[i].SubItems[n].Text);
                        }
                    }
                }

            }
            Clipboard.SetText(strbuilder.ToString());
        }
        //复制整列
        void CopyColumn()
        {
            if (index<0)
            {
                return;
            }
            StringBuilder str = new StringBuilder();
            for (int i = 0; i < lvMatchecs.Items.Count; i++)
            {
                str.Append(lvMatchecs.Items[i].SubItems[index].Text + "\n");
            }
            Clipboard.SetText(str.ToString());
        }

        private void 移除本列ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            lvMatchecs.Columns.RemoveAt(index);
        }

        private void 复制整列ToolStripMenuItem_Click_1(object sender, EventArgs e)
        {
            CopyColumn();
        }

        private void btn_clear_Click(object sender, EventArgs e)
        {
            txt_regex_txt.Text = "";
        }

        private void btn_replice_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                btn_matching_Click(sender, e);
            }

        }

        private void txt_PostUrl_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                btn_Submit_Click(sender, e);
            }
        }

        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            if (cms_txt.SourceControl.Text != "")
            {
                Clipboard.SetText(cms_txt.SourceControl.Text);
                cms_txt.SourceControl.Text = "";
            }
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            tabControl1.SelectedIndex = 0;
        }

        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            tabControl1.SelectedIndex = 1;
        }

        private void toolStripButton3_Click(object sender, EventArgs e)
        {
            tabControl1.SelectedIndex = 2;
        }

        private void option_Click(object sender, EventArgs e)
        {
            Frm_option option = new Frm_option();
            if (option.ShowDialog() == DialogResult.OK)
            {

            }
        }

        private void btn_gethttp_Click(object sender, EventArgs e)
        {
            string url = InputBox("网址设置", "请输入要获取源码的网址", "http://");
            if (url != "")
            {
                HttpHelper http = new HttpHelper();
                HttpItem item = new HttpItem() { Method = "GET", URL = url };
                HttpResult result = http.GetHtml(item);
                txt_regex_txt.Text = result.Html.ToString();
            }
        }

        private void btn_get_returndata_Click(object sender, EventArgs e)
        {
            txt_regex_txt.Text = txt_Returndata.Text;
        }

        private void Fm_Main_Resize(object sender, EventArgs e)
        {

        }

        private void btnRegexCode_Click(object sender, EventArgs e)
        {

            txt_regex.Text = RegexCode(txt_regex.Text);
        }
        private string RegexCode(string RegexStr)
        {
            string temp = RegexStr;
            temp = temp.Replace("\\", "\\\\");
            temp = temp.Replace("\"", "\\\"");
            return temp;
        }
        private string RegexDecode(string RegexStr)
        {
            string temp = RegexStr;
            temp = temp.Replace("\\\"", "\"");
            temp = temp.Replace("\\\\", "\\");
            return temp;
        }

        private void btnRegexDecode_Click(object sender, EventArgs e)
        {
            txt_regex.Text = RegexDecode(txt_regex.Text);
        }

        private void btnEncode_Click(object sender, EventArgs e)
        {
            EncodeConver ec = new EncodeConver();
            if (cmbConvert.SelectedIndex != 0)
            {
                txtCodeNew.Text = ec.Encode(cmbConvert.Text, txtCodeOld.Text, cmbEncoding.Text);
            }
            else
            {
                StringBuilder sb = new StringBuilder();
                foreach (var item in cmbConvert.Items)
                {
                    if (item.ToString() == "ALL") continue;
                    sb.AppendLine(item + "结果： ");
                    sb.AppendLine(ec.Encode(item.ToString(), txtCodeOld.Text, cmbEncoding.Text));
                }
                txtCodeNew.Text = sb.ToString();
            }
        }

        private void btnDecode_Click(object sender, EventArgs e)
        {
            EncodeConver ec = new EncodeConver();
            if (cmbConvert.SelectedIndex != 0)
            {
                txtCodeNew.Text = ec.Decode(cmbConvert.Text, txtCodeOld.Text, cmbEncoding.Text);
            }
            else
            {
                StringBuilder sb = new StringBuilder();
                foreach (var item in cmbConvert.Items)
                {
                    if (item.ToString() == "ALL") continue;
                    sb.AppendLine(item + "结果： ");
                    sb.AppendLine(ec.Decode(item.ToString(), txtCodeOld.Text, cmbEncoding.Text));
                }
                txtCodeNew.Text = sb.ToString();
            }
        }

        private void Posttest_Click(object sender, EventArgs e)
        {

        }



        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            time.Visible = time2.Visible = status.Visible = false;
            if (tabControl1.SelectedIndex == 0)
            {
                time.Visible = true;
            }
            if (tabControl1.SelectedIndex == 1)
            {
                time2.Visible = true;
                status.Visible = true;
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            (txtTo.Text, txtFrom.Text) = (txtFrom.Text, txtTo.Text);
        }

        private void cmbFanyiType_SelectedIndexChanged(object sender, EventArgs e)
        {
            cmbfrom.Items.Clear();
            cmbTo.Items.Clear();
            if (cmbFanyiType.SelectedIndex == 0 || cmbFanyiType.SelectedIndex == 2)
            {
                foreach (var item in baidutype)
                {
                    cmbfrom.Items.Add(item);
                    cmbTo.Items.Add(item);
                }
            }
            if (cmbfrom.Items.Count > 0)
            {
                cmbfrom.SelectedIndex = 0;
                cmbTo.SelectedIndex = 0;
            }

            cmbfrom.Enabled = cmbTo.Enabled = (cmbFanyiType.SelectedIndex != 1);


        }
        object[] baidutype = new object[0];
        private void InitType()
        {
            List<ItemClass> listbaidu = new List<ItemClass>
            {
                new ItemClass("自动检测", "auto"),
                new ItemClass("中文", "zh"),
                new ItemClass("英语", "en"),
                new ItemClass("粤语", "yue"),
                new ItemClass("文言文", "wyw"),
                new ItemClass("日语", "jp"),
                new ItemClass("韩语", "kor"),
                new ItemClass("法语", "fra"),
                new ItemClass("西班牙语", "spa"),
                new ItemClass("泰语", "th"),
                new ItemClass("阿拉伯语", "ara"),
                new ItemClass("俄语", "ru"),
                new ItemClass("葡萄牙语", "pt"),
                new ItemClass("德语", "de"),
                new ItemClass("意大利语", "it"),
                new ItemClass("希腊语", "el"),
                new ItemClass("荷兰语", "nl"),
                new ItemClass("波兰语", "pl"),
                new ItemClass("保加利亚语", "bul"),
                new ItemClass("爱沙尼亚语", "est"),
                new ItemClass("丹麦语", "dan"),
                new ItemClass("芬兰语", "fin"),
                new ItemClass("捷克语", "cs"),
                new ItemClass("罗马尼亚语", "rom"),
                new ItemClass("斯洛文尼亚语", "slo"),
                new ItemClass("瑞典语", "swe"),
                new ItemClass("匈牙利语", "hu"),
                new ItemClass("繁体中文", "cht"),
                new ItemClass("越南语", "vie")
            };
            baidutype = listbaidu.ToArray();
        }

        private void btnTranslate_Click(object sender, EventArgs e)
        {
            string from = "";
            string to = "";
            if (cmbfrom.Items.Count > 0)
            {
                from = ((ItemClass)cmbfrom.SelectedItem).Value;
                to = ((ItemClass)cmbTo.SelectedItem).Value;
            }
            string result = "翻译中";
            txtTo.Text = result; Application.DoEvents();
            if (cmbFanyiType.SelectedIndex == 0)
            {
                FanYi fanyi = new FanYi();
                result = fanyi.Fanyi(txtFrom.Text, from, to);

            }
            else if (cmbFanyiType.SelectedIndex == 1)
            {
                FanyiYouDao fanyi = new FanyiYouDao();
                result = fanyi.Fanyi(txtFrom.Text);

            }

            else
            {
                result = "未选择正确的翻译语言";
            }
            txtTo.Text = result;
        }

        private void btnSpeechFrom_Click(object sender, EventArgs e)
        {
            Speeck(txtFrom.Text);
        }
        private void btnSpeechTo_Click(object sender, EventArgs e)
        {
            Speeck(txtTo.Text);
        }
        private void Speeck(string msg)
        {
            string phrase = msg;
            SpeechSynthesizer speech = new SpeechSynthesizer();
            CultureInfo keyboardCulture = System.Windows.Forms.InputLanguage.CurrentInputLanguage.Culture;
            InstalledVoice neededVoice = speech.GetInstalledVoices(keyboardCulture).FirstOrDefault();
            speech.Rate = tbRate.Value;
            if (neededVoice == null)
            {
                phrase = "Unsupported Language";
            }
            else if (!neededVoice.Enabled)
            {
                phrase = "Voice Disabled";
            }
            else
            {
                speech.SelectVoice(neededVoice.VoiceInfo.Name);
            }

            speech.SpeakAsync(phrase);

        }
        private void SaveSpeeck(string Msg)
        {
            string phrase = Msg;
            SpeechSynthesizer speech = new SpeechSynthesizer();

            CultureInfo keyboardCulture = System.Windows.Forms.InputLanguage.CurrentInputLanguage.Culture;
            InstalledVoice neededVoice = speech.GetInstalledVoices(keyboardCulture).FirstOrDefault();
            speech.Rate = tbRate.Value;
            if (neededVoice == null)
            {
                phrase = "Unsupported Language";
            }
            else if (!neededVoice.Enabled)
            {
                phrase = "Voice Disabled";
            }
            else
            {
                speech.SelectVoice(neededVoice.VoiceInfo.Name);
            }
            speech.Rate = tbRate.Value;

            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Title = "保存文档";
            saveFileDialog.Filter = "*.wav|*.wav|*.mp3|*.mp3";
            saveFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            DialogResult saveDialog = saveFileDialog.ShowDialog();
            try
            {

                if (saveDialog == DialogResult.OK)
                {
                    speech.SetOutputToWaveFile(saveFileDialog.FileName);
                    speech.Speak(phrase);
                    speech.SetOutputToNull();
                    System.Diagnostics.Process.Start("Explorer.exe", string.Format(@"/select,{0}", saveFileDialog.FileName));//打开wav目录并选中文件
                }

            }
            catch (Exception er)
            {
                MessageBox.Show(er.ToString(), "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnSpeechFrom_MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button==MouseButtons.Right)
            {
                SaveSpeeck(txtFrom.Text);
            }
        }

        private void btnSpeechTo_MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                SaveSpeeck(txtTo.Text);
            }
        }
        private void txt_TextChanged(object sender, EventArgs e)
        {
            //lineChange = !lineChange;
            //if (lineChange)
            //{
            //    TextBox tb = sender as TextBox;
            //    //tb.Text = tb.Text.Replace("\r\n", System.Environment.NewLine).Replace("\n", System.Environment.NewLine);
            //    tb.Text = tb.Text.Replace("\n", "\r\n").Replace("\r\n\n", "\r\n");
            //}


        }

        Regex regMakeI = new Regex("{((i)([\\+\\-\\*\\\\\\÷]\\d+)?)}");
        private void btnMake_Click(object sender, EventArgs e)
        {
            try
            {
                string tpl = txtMakeTpl.Text;
                Match match = regMakeI.Match(tpl);
                StringBuilder sb = new StringBuilder();
                int columns = lvMatchecs.Columns.Count - 2;
                for (int i = 0; i < lvMatchecs.Items.Count; i++)
                {

                    string[] strs = new string[columns];
                    for (int i2 = 2; i2 < lvMatchecs.Columns.Count; i2++)
                    {
                        strs[i2 - 2] = lvMatchecs.Items[i].SubItems[i2].Text;
                    }
                    string r = tpl;
                    if (match.Success)
                    {
                        string js = match.Groups[1].Value.Replace("i",i.ToString());
                        string jr = Calc(js).ToString();
                        r = r.Replace(match.Value, jr);
                    }
                    r = string.Format(r, strs);
                    sb.Append(r);
                }
                txtMakeResult.Text = sb.ToString();
            }
            catch (Exception ex)
            {

                txtMakeResult.Text = "生成失败：" + ex.Message;
            }
            
        }
        public object Calc(string expression)
        {
            string className = "Calc";
            string methodName = "Run";
            expression = expression.Replace("/", "*1.0/");

            //  创建编译器实例。 
            ICodeCompiler complier = (new CSharpCodeProvider().CreateCompiler());
            //  设置编译参数。 
            CompilerParameters paras = new CompilerParameters();
            paras.GenerateExecutable = false;
            paras.GenerateInMemory = true;

            //  创建动态代码。 
            StringBuilder classSource = new StringBuilder();
            classSource.Append("public  class  " + className + "\n");
            classSource.Append("{\n");
            classSource.Append("        public  object  " + methodName + "()\n");
            classSource.Append("        {\n");
            classSource.Append("                return  " + expression + ";\n");
            classSource.Append("        }\n");
            classSource.Append("}");

            //System.Diagnostics.Debug.WriteLine(classSource.ToString()); 

            //  编译代码。 
            CompilerResults result = complier.CompileAssemblyFromSource(paras, classSource.ToString());

            //  获取编译后的程序集。 
            Assembly assembly = result.CompiledAssembly;

            //  动态调用方法。 
            object eval = assembly.CreateInstance(className);
            MethodInfo method = eval.GetType().GetMethod(methodName);
            object reobj = method.Invoke(eval, null);
            GC.Collect();
            return reobj;

        }

        private void 复制整列ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            CopyColumn();
        }
    }
    class ItemClass
    {
        private string _Text = "";
        private string _Value = "";

        public ItemClass(string _Text, string _Value)
        {
            this._Text = _Text;
            this._Value = _Value;
        }

        public string Text
        {
            get
            {
                return _Text;
            }

            set
            {
                _Text = value;
            }
        }

        public string Value
        {
            get
            {
                return _Value;
            }

            set
            {
                _Value = value;
            }
        }
        public override string ToString()
        {
            return Text;
        }
    }
    
}
